﻿using System;
using System.Collections.Generic;
using System.Linq;
using theeg.DependencyAnalysis.CommonAddin.Models;

namespace theeg.DependencyAnalysis.VsAddin2012
{
    public class VsSolution : ISolution
    {
        private readonly EnvDTE.Solution _dteSolution;

        public Action BuildFinished { get; set; }
        public string FileName { get { return _dteSolution.FileName; } }

        public IList<IProject> Projects { get; private set; }

        public VsSolution(EnvDTE.Solution solution)
        {
            _dteSolution = solution;
        }

        public void Refresh()
        {
            var solutionProjects = new List<EnvDTE.Project>();
            foreach (EnvDTE.Project project in _dteSolution.Projects)
            {
                if (project.Kind == ProjectKindSolutionFolder)
                {
                    solutionProjects.AddRange(GetSolutionFolderProjects(project));
                }
                else
                {
                    solutionProjects.Add(project);
                }
            }
            var projects = (from project in solutionProjects
                            where VsProject.IsClrProject(project)
                            orderby project.Name
                            select new VsProject(project) { Name = project.Name, IsSelected = true }).Cast<IProject>().ToList();
            Projects = projects;
        }

        public void Build()
        {
            _dteSolution.SolutionBuild.Build(true);
            var handler = BuildFinished;
            if (handler != null)
            {
                handler();
            }
        }

        private const string ProjectKindSolutionFolder = "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}";
        private static IEnumerable<EnvDTE.Project> GetSolutionFolderProjects(EnvDTE.Project solutionFolder)
        {
            for (var i = 1; i <= solutionFolder.ProjectItems.Count; i++)
            {
                var subProject = solutionFolder.ProjectItems.Item(i).SubProject;
                if (subProject == null)
                {
                    continue;
                }

                if (subProject.Kind == ProjectKindSolutionFolder)
                {
                    foreach (var x in GetSolutionFolderProjects(subProject))
                    {
                        yield return x;
                    }
                }
                else
                {
                    yield return subProject;
                }
            }
        }
    }
}
